<template>
  <div>
    <row-vet></row-vet>
    <!-- 搜索输入框 -->
    <form action="/">
      <van-search
        v-model="queryValue"
        class="search"
        placeholder="请输入搜索关键词"
        show-action
        @input="onSearch"
        @cancel="onCancel"
        @clear="onClear"
        @search="onGoodsList"
      />
    </form>
    <!-- 历史记录,根据搜索框键入值判断是否保留 -->
    <div v-if="queryValue.length ==0 && localSearchHistory !== null? true : false ">
      <van-row v-if="historyHidden">
        <van-col span="22">
          <span class="historyTitle">历史记录：</span>
          <van-tag
            round
            v-for="(item, index) in localSearchHistory"
            :key="index"
            class="historyTags"
            @click="tagTouch(item)"
          >{{item}}</van-tag>
        </van-col>
        <van-col span="2">
          <van-icon name="delete" @click="removeStorageQuery" size="16px" />
        </van-col>
      </van-row>
    </div>
    <!-- 搜索结果列表 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
    >
      <van-cell
        v-for="item in queryResult"
        :key="item.goods_id"
        :title="item.goods_name"
        @click="showGoodsid(item.goods_id)"
      />
    </van-list>
    <row-vit></row-vit>
  </div>
</template>
<script>
import minfo from '../util/navigation'
import header from '../util/header'
export default {
  data() {
    return {
      isLoading: false,
      // 搜索关键字
      queryValue: '',
      // 搜索结果列表
      queryResult: [],
      // 控制van-list是否加载
      loading: false,
      // 控制van-list加载完成
      finished: false,
      error: false,
      // 历史搜索记录
      searchHistory: [],
      localSearchHistory: [],
      historyHidden: false
    }
  },
  components: {
    'row-vit': minfo,
    'row-vet': header
  },
  created() {
    this.getHistory()
  },
  methods: {
    onRefresh() {
      setTimeout(() => {
        this.$toast('刷新成功')
        this.isLoading = false
        this.count++
      }, 1000)
    },
    // 从localStorage获取item，渲染界面
    getHistory() {
      if (localStorage.getItem('searchHistory')) {
        this.localSearchHistory = JSON.parse(
          localStorage.getItem('searchHistory')
        )
        this.historyHidden = true
      } else {
        this.historyHidden = false
        return
      }
    },
    // 输入框内容改变时触发搜索功能
    async onSearch() {
      const data = await this.$axios.get('/goods/qsearch', {
        params: { query: this.queryValue }
      })
      this.queryResult = data.message
    },
    // 向localStorage里存储历史记录
    setLocalHistory() {
      //如果localstorage中有搜索历史，先取出localstorage中储存的searchHistory放入searchHistory中
      if (localStorage.getItem('searchHistory')) {
        this.searchHistory = JSON.parse(localStorage.getItem('searchHistory'))
      }
      this.searchHistory.push(this.queryValue)
      // 数组去重，再存localStorage
      this.searchHistory = [...new Set(this.searchHistory)]
      localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory))
    },
    // search事件触发时跳转至商品列表页面
    onGoodsList() {
      if (this.queryValue.trim().length === 0) return
      this.$router.push({
        name: '/gooddate',
        params: { name: this.queryValue }
      })
      this.setLocalHistory()
    },
    cleanData() {
      // 清空关键字
      this.queryValue = ''
      this.queryResult = []
      this.finished = false
      this.getHistory()
    },
    // 点击取消清空搜索框内容
    onCancel() {
      this.cleanData()
    },
    // 点击x号清空搜索框内容
    onClear() {
      this.cleanData()
    },
    onLoad() {
      // 如果搜索框两端去空有值
      if (this.queryValue.trim().length !== 0) {
        // 异步更新数据
        setTimeout(() => {
          // 加载状态结束
          this.loading = false
          // 数据全部加载完成
          this.finished = true
        }, 500)
      } else {
        this.loading = false
      }
    },
    // 点击历史记录标签重新搜索
    tagTouch(goodsName) {
      this.queryValue = goodsName
      this.onSearch()
    },
    //点击跳转到商品界面
    showGoodsid(id) {
      this.setLocalHistory()
      this.$router.push('/goodlist/' + id)
    },
    //点击删除清除历史记录
    removeStorageQuery() {
      localStorage.removeItem('searchHistory')
      this.localSearchHistory = []
      this.getHistory()
    }
  }
}
</script>

<style lang="less" scoped>
.title {
  height: 1.2rem;
  background-color: #d81e06;
  color: #ffffff;
  position: relative;
  .van-button {
    background-color: #d81e06;
    border: none;
    color: #ffffff;
  }

  .title_hm {
    height: 100%;
    line-height: 1.2rem;
    text-align: center;
    font-family: '微软雅黑';
    font-size: 0.5rem;
  }
}
.search {
  margin-top: 1.2rem;
}
.historyTitle {
  font-size: 14px;
  margin-left: 10px;
}
.historyTag {
  margin: 4px;
}
.historyTags {
  margin-left: 3px;
  background-color: #ccc;
}
</style>